package com.carefree.bookmall.filter;

import com.carefree.bookmall.entity.User;
import jakarta.servlet.annotation.WebFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName:AdminFilter
 * @Description:
 * @Author qianyue
 */
@WebFilter(filterName = "AdminFilter", urlPatterns = "/bookmall/admin/*")
public class AdminFilter implements Filter {


    /**
     * 初始化
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    /**
     * 放行
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        User sessionUser = (User) httpServletRequest.getSession().getAttribute("usered");
        if (ObjectUtils.isEmpty(sessionUser) || sessionUser.getRoleId() != 1) {
            httpServletResponse.sendRedirect("/bookmall/index");
        } else {
            chain.doFilter(request, response);
        }
    }


    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
}
